import React, { useEffect, useState } from 'react'
import style from './cardEmployee.module.scss'
import { IPeriod, IProjectToEmployeeLink } from '../../../starter/model/interfaces'
import {useDrag} from 'react-dnd'
import dayjs from 'dayjs'
import { DATE_FORMAT } from '../../../starter/constants'
import { Progress } from 'antd'
import PersonContactSet from '../PersonContactSet/PersonContactSet'

type TCardEmployee = {
  linkItem: IProjectToEmployeeLink
  isSmall: boolean

}
export default function CardEmployee ({ linkItem, isSmall}: TCardEmployee) {

  const [barPercent, setBarPercent] = useState<number>(0)
  const [currentPeriod, setCurrentPeriod] = useState<IPeriod>()

  useEffect(() => {
    const _currentPeriod = linkItem.periods.find(p => dayjs(p.startTime) <= dayjs() && dayjs() <= dayjs(p.endTime))

    if (_currentPeriod) {
      setCurrentPeriod(_currentPeriod)
    }

  }, [linkItem.periods])

  useEffect(() => {
    if (currentPeriod) {
      const allPeriodLength = dayjs(currentPeriod.endTime).diff(dayjs(currentPeriod.startTime), 'days')
      const currentPeriodLength = dayjs().diff(dayjs(currentPeriod.startTime), 'days')
      const percent = Math.round(100 * currentPeriodLength / allPeriodLength)
      setBarPercent(percent)
    }
  }, [currentPeriod])

  const [monitor,employeeRef, employeePreviewRef] = useDrag({
    type: 'employee',
    item: linkItem,
    collect: monitor => monitor
  })

  const calcBarColor = (percent: Number) => {
    if (percent > 0 && percent < 75) return 'green'
    if (percent >= 75 && percent <= 100) return '#ead503'
    if (percent >100) return 'red'
  }
  return (
    <div
      className={style.wrapper}
      ref={employeeRef}
    >
      <div  className={style.title}>{linkItem.employee.firstName} {linkItem.employee.lastName}</div>
      <div className={style.info}>
        <PersonContactSet person={linkItem.employee}/>
        <div className={style.endTime}>
          {/*поставить посчитанный актуальный период*/}
          {dayjs(currentPeriod && currentPeriod.endTime).format(DATE_FORMAT)}
        </div>
      </div>

      <div className={style.progressBar}>
        <Progress
          percent={barPercent}
          showInfo={barPercent < 100 && true}
          strokeColor={calcBarColor(barPercent)}
        />
      </div>
    </div>
  )
}
